package com.kaifamiao.lifecycle;

import com.kaifamiao.util.JdbcHelper;
import com.kaifamiao.util.RowHandler;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class PositiveServlet extends GenericServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    private JdbcHelper helper ;

    // 这个方法是由 GenericServlet 定义的专供子类重写的
    @Override
    public void init() throws ServletException {
        logger.info( "初始化: " + this.getServletName() );
        helper = JdbcHelper.getInstance();
    }

    @Override
    public void service(ServletRequest req , ServletResponse resp)
            throws ServletException, IOException {
        logger.info( "提供服务" );
        String sql = "SELECT empno , ename , job , sal FROM emp";
        RowHandler< Map<String,Object> > handler = new RowHandler<>() {
            @Override
            public Map<String, Object> handle(ResultSet rs) throws SQLException {
                Map<String, Object> map = new HashMap<>();
                map.put( "empno" , rs.getObject( "empno" ) );
                map.put( "ename" , rs.getObject( "ename" ) );
                map.put( "job" , rs.getObject( "job" ) );
                map.put( "sal" , rs.getObject( "sal" ) );
                return map;
            }
        };
        List< Map<String,Object> >  list = helper.query( sql , handler );

        req.setCharacterEncoding( "UTF-8" );
        resp.setCharacterEncoding( "UTF-8" );

        resp.setContentType( "text/html" );

        PrintWriter out = resp.getWriter();

        out.println( "<table border=\"1\">" );
        for(Iterator<Map<String,Object>> itor = list.iterator() ; itor.hasNext() ; ){
            Map<String,Object> map = itor.next();
            out.println( "<tr>");
            for( Map.Entry<String,Object> entry : map.entrySet() ){
                out.println( "<td>" + entry.getKey() + " </td>");
                out.println( "<td>" + entry.getValue() + " </td>");
            }
            out.println( "</tr>");
        }
        out.println( "</table>" );
    }

    @Override
    public void destroy() {
        logger.info( "销毁" );
        helper.release();
    }
}
